package com.edu;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main {

    public static void main(String[] args) {

        Person person = new Person();
        person.setUuid(11111);
        person.setId(100);
        person.setNickName("sivler");

        String query = query(person);
        System.out.println(query);
    }

    private static String query(Object p) {
        StringBuilder sb = new StringBuilder();
        // 1、获取到class
        Class c = p.getClass();
        // 获取到table的名字
        boolean exit = c.isAnnotationPresent(Table.class);
        if (!exit) {
            return null;
        }
        Table table = (Table) c.getAnnotation(Table.class);
        String tableName = table.value();
        sb.append("select * from ").append(tableName).append(" where 1=1");
        // 3、遍历所有的字段
        for (Field f : c.getDeclaredFields()) {
            boolean fexists = f.isAnnotationPresent(Column.class);
            if (!fexists) {
                continue;
            }
            Column column = f.getAnnotation(Column.class);
            String columnName = column.value();

            String methodName = "get" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);
            Object columnValue = null;
            try {
                Method method = c.getMethod(methodName);
                columnValue = method.invoke(p);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (columnValue != null) {
                if (columnValue instanceof String){
                    sb.append(" and ").append(columnName).append("=").append("'").append(columnValue).append("'");
                }
                if (columnValue instanceof Integer){
                    sb.append(" and ").append(columnName).append("=").append(columnValue);
                }
            }
        }
        return sb.toString();
    }
}
